<template>
  <div style="padding: 15px;">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px"  v-loading.fullscreen.lock="isDisable">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="上架单号">
              <el-input v-model="form.putawayCode" style="width:75%" :disabled="true"  />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="收货单号">
              <el-input v-model="form.receiveCode" style="width:75%" :disabled="true"  />
            </el-form-item>
          </div>
        </el-col>

        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="所属仓库" >
              <el-select v-model="form.warehouseCode" placeholder="请输入所属仓库  " style="width:75%" :disabled="true">
                <el-option
                  v-for="item in warehouseData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="入驻商" >
              <el-input v-model="form.shipmentName" style="width:75%" :disabled="true"  />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="操作员" prop="operatorName">
              <el-input v-model="form.operatorName" style="width:75%" placeholder="请输入操作员" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="19">
          <div class="grid-content bg-purple">
            <el-form-item  label="备注" prop="remarks" >
              <el-input v-model="form.remarks" style="width:75%" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      border
      resizable
      show-overflow
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      :span-method="objectSpanMethod"
      show-footer
      :footer-method="footerMethod"
      :edit-rules="validRules"
      @edit-actived="editActiveEvent"
      auto-resize
      :edit-config="{trigger: 'click', mode: 'cell'}">
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column field="goodsName" title="商品名称"  width="270"></vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位"  width="120" ></vxe-table-column>
      <vxe-table-column field="receivedQuantity" title="收货数量"  width="120"></vxe-table-column>
      <vxe-table-column field="containerBarCode" title="容器号"  width="120" ></vxe-table-column>
      <vxe-table-column field="recommendLocationName" title="推荐库位"  width="120" ></vxe-table-column>
      <vxe-table-column  field="goodsStatusName" title="货品状态" width="120" ></vxe-table-column>
      <vxe-table-column field="statusName" title="上架状态" width="120" ></vxe-table-column>
      <vxe-table-column field="putawayQuantity" title="上架数量" :edit-render="{name: 'input', attrs: {disabled: editActive}}" width="120"></vxe-table-column>
      <vxe-table-column field="locationName" title="上架库位" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <locationSelect :val1="form.warehouseCode" ref="locationSelect" :val2="editActive"  @setGoodsCode="setLocationCode(row)" />
        </template>
      </vxe-table-column>

      <vxe-table-column field="gmtManufacture" title="生产日期"   width="120"></vxe-table-column>
      <vxe-table-column field="gmtExpire" title="过期日期" width="120"></vxe-table-column>
      <vxe-table-column field="taskCode" title="任务号" width="120"></vxe-table-column>
      <vxe-table-column field="operatorName" title="作业人" width="120"></vxe-table-column>
      <vxe-table-column field="remarks" title="备注"  width="270"></vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="150">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="拆分" placement="top" v-if="scope.row.isShow == '0' && scope.row.status == '0'">
            <vxe-button type="text" @click="insertEvent(tableData[scope.row.num + 1],scope.row)">
              <i class="iconfont icon-zhuangchedanguanli" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top" v-if="scope.row.isShow == '1' && scope.row.status == '0'">
            <vxe-button type="text" @click="remove(scope.row)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>

    </vxe-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSubmitSave" :disabled="isDisable" plain>保 存</el-button>
      <el-button type="primary" @click="funcSubmitCheck" :disabled="isDisable" plain>提 交</el-button>
    </div>

  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
import request from '@/utils/request'
import VXETablePluginElement from 'vxe-table-plugin-element'
import 'vxe-table-plugin-element/dist/style.css'
import { validatePhone, validateIDNumber } from "@/utils/validate.js";
import locationSelect from '@/views/components/locationsElSelect.vue'
import {getWarehouse} from '@/api/basicInfo'
import { goodsUnitConversion, putawayCheckSubmit ,putawaySaveSubmit} from '@/api/inStorage'
import shipmentSelect from '@/views/components/shipmentSelect.vue'
import {  putawayDetail} from '@/api/inStorage'
import '@/assets/iconfont/iconfont.css';
import { isNumber } from '@/utils/validate.js'

Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
VXETable.use(VXETablePluginElement)
export default {
  name: 'Parent',
  components: {
    locationSelect,
    shipmentSelect
  },
  data() {
    return {
      allAlign:'center',
      testArr1: [],
      testArr2: [],
      testArr3: [],
      testArr4: [],
      testArr5: [],
      testPosition1: 0,
      testPosition2: 0,
      testPosition3: 0,
      testPosition4: 0,
      testPosition5: 0,
      start:'0',
      spanArr: [], // 一个空的数组，用于存放每一行记录的合并数
      pos: 0, // spanArr 的索引
      contentSpanArr: [],
      position: 0      ,
      warehouseData:[],
      isDisable:false,   //确定键显示按钮

      units:[],
      isDisable:false,   //确定键显示按钮
      form: {
        shipmentCode: '',
        type:'0',
        warehouseCode:"",
        shipmentName:'',
        receiveCode:'',
        operatorName:'',
        putawayCode:'',
        sourceCode:'',
        supplierCode:'',
        remarks: '', // 备注
        gmtPlanArrival: '',
        putawayRegisterWithItemVOS: []
      },
      loading: false,
      tableData: [
      ],
      rules: {
        shipmentCode: [
          { required: true, message: '请输入客户姓名', trigger: 'change' }
        ],
        warehouseCode: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        supplierCode: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        operatorName: [
          {max: 50, message: '操作员最多50个字符', trigger: 'change'},
        ],
        remarks: [
          {max: 100, message: '备注最多100个字符', trigger: 'change'},
        ],

      },
      validRules: {
        putawayQuantity: [
          { required: true, message: '上架数量必须填写' },
          { pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d{0,6})$/, message: '小数点后保留六位小数' },
          { max: 18, message: '上架数量过大'}
        ],
        locationName: [
          { required: true, message: '上架库位必须填写' },
        ],
        planQuantity: [
          { required: true, message: '数量必须填写' },
        ],
      },
      listQuery: {
        page: 1,
        limit: 13,
        totalzong: 0
      },
      // 上架确认信息是否可编辑标志位
      editActive: false,
    }
  },
  created() {
    this.getWarehouse()
  },
  methods: {
    // 表格合并行
    objectSpanMethod({ row, rowIndex,column,  columnIndex }) {
      if(this.start == 1){
        if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5 ) {
          const _row = this.spanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          };
        }
      }
    },
    //库位选择
    setLocationCode(row){
      let obj = this.$refs.locationSelect.obj
      row.locationName = obj.serialNumber
      row.location = obj.code
      row.spaceCode = obj.spaceCode
    },

    formatGoodsStatus({cellValue}){
      if(cellValue == '0'){
        return '合格'
      }else if(cellValue == '1'){
        return '不合格'
      }
    },
    remove(row){
      this.$refs.xTable.remove(row)
      this.tableData = this.$refs.xTable.tableData
      this.tableData.forEach( (i,index) => {
        if(i.num){
          i.num = index
        }
      })
      this.calcMergeCell();
    },
    insertEvent (row,Row) {
      if(row == undefined){
        row = -1
      }
      // 复制一份，清除掉库区、库位、上架数量
      let record = JSON.parse(JSON.stringify(Row));
      record.location = '';
      record.locationName = '';
      record.spaceCode = '';
      record.putawayQuantity = '';
      record.isShow = 1;
      record.num = Row.num;
      record.status = 0;

      let { row: newRow } = this.$refs.xTable.insertAt(record, row)
      this.$refs.xTable.setActiveCell(newRow, 'isShow')
      this.tableData = this.$refs.xTable.tableData
      this.tableData.forEach( (i,index) => {
        if(i.num){
          i.num = index
        }
      })
      this.calcMergeCell();
    },
    // 获取页面信息
    getInfo() {
      this.loading = true
      let code = this.$route.query.code ? this.$route.query.code : "";
        putawayDetail(code).then(response => {
          this.form = response.data
          this.form.putawayCode = response.data.code
          response.data.putawayRegisterWithItemVOS.forEach(item => {
            // 上架数量默认收货数量
            item.putawayQuantity = item.receivedQuantity
            // 根据推荐库位 自动 回填上架库位
            if (item.recommendLocation) {
              item.locationName = item.recommendLocationName
              item.location = item.recommendLocation
              item.spaceCode = item.recommendSpaceCode
            }
          });
          this.tableData = response.data.putawayRegisterWithItemVOS
          this.calcMergeCell();

          for (let i = 0; i < this.tableData.length; i++) {
            this.tableData[i].num = i
          }
          // this.tableData.forEach( i => {
          //   i.isShow = 0
          // })
          this.loading = false

      }).then(()=>{

        })
    },
    // 计算合并单元格范围
    calcMergeCell(){
      this.start = 1
      this.spanArr = [];
      this.contentSpanArr = [];
      for (var i = 0; i < this.tableData.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0;
          this.contentSpanArr.push(1);
          this.position = 0;
          this.tableData[i].isShow = 0;
        } else {
          // 判断当前元素与上一个元素是否相同(第1和第2列)
          if (this.tableData[i].receiveRegisterCode == this.tableData[i - 1].receiveRegisterCode) {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);

            if (this.tableData[i - 1].status == 2) {
              this.tableData[i].isShow = 0;
            } else {
              this.tableData[i].isShow = 1;
            }
          } else {
            this.spanArr.push(1);
            this.pos = i;
            this.tableData[i].isShow = 0;
          }

        }
      }
    },
    //仓库查询
    getWarehouse(){
      getWarehouse().then(response => {
        this.warehouseData = response.data
        // this.initLocationSelectInfo();
      })
      this.getInfo()
    },
    // 提交
    funcSubmitCheck() {
      let flag = false;
      this.form.putawayRegisterWithItemVOS = this.$refs.xTable.tableData

      this.form.putawayRegisterWithItemVOS.some((i,index)=>{
        if(!this.validatePutawayQuantity(i.putawayQuantity)){
          this.$message({ message: '第' + (index+1) + "行上架数量必须为数字", type: 'error' });
          flag = true;
          return flag;
        }
      })

      if(flag){
        return;
      }

      const data = this.form
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$refs.xTable.validate((valids) => {
            if(valids){
              this.isDisable = true
              putawayCheckSubmit(data).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.$emit('fatherAddMethod')
                this.isDisable = false
              }).then(() => {
                this.$eventBus.$emit('refreshList')
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$router.push({
                  path: "/inbound/putaway"
                });
              }).catch(() => this.isDisable = false)
            }
          })
        }
      });
    },

    // 保存
    funcSubmitSave() {
      let flag = false;
      this.form.putawayRegisterWithItemVOS = this.$refs.xTable.tableData

      this.form.putawayRegisterWithItemVOS.some((i,index)=>{
        if(!this.validatePutawayQuantity(i.putawayQuantity)){
          this.$message({ message: '第' + (index+1) + "行上架数量必须为数字", type: 'error' });
          flag = true;
          return flag;
        }
      })

      if(flag){
        return;
      }

      const data = this.form
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$refs.xTable.validate((valids) => {
            if(valids){
              this.isDisable = true
              putawaySaveSubmit(data).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.$emit('fatherAddMethod')
                this.isDisable = false
              }).then(() => {
                this.$eventBus.$emit('refreshList')
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$router.push({
                  path: "/inbound/putaway"
                });
              }).catch(() => this.isDisable = false)
            }
          })
        }
      })

    },

  /*  initLocationSelectInfo(){
      this.$refs.locationSelect.
    },*/


    footerMethod ({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 1) {
            return '合计'
          }

          if (['receivedQuantity'].includes(column.property)) {
            return this.form.totalQuantity
          }
          if (['putawayQuantity'].includes(column.property)) {
              return XEUtils.sum(data, column.property).toFixed(6)
          }
          return '-'
        })
      ]
    },
    validatePutawayQuantity(putawayQuantity){
      if(putawayQuantity == null || putawayQuantity == '' || isNumber(putawayQuantity)){
        return true;
      }
      return false;
    },


    // 已拣货的拣货数量禁止编辑
    editActiveEvent ({ rowIndex, row }) {
      this.editActive = row.status != '0'
    },
  }

}
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 150px auto;
    width: 175px;
    // float: right;
  }
  </style>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
